package com.test.excelservice.controller;

import com.alibaba.excel.EasyExcel;
import com.test.excelservice.generateor.GeneratorUtils;
import com.test.excelservice.model.GeneInfo;
import com.test.excelservice.model.ReqParam;
import com.test.excelservice.model.ResParam;
import com.test.excelservice.result.Result;
import com.test.excelservice.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 解析excel信息生成tag
 * @author shilei
 */
@RestController
public class ExcelController {

    private Logger logger = LoggerFactory.getLogger(ExcelController.class);

    private  Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");

    @RequestMapping("/parse/file")
    public Result<List<GeneInfo>> pareExcel(MultipartFile file, GeneInfo geneInfo) {

        try{
            logger.info("读取"+file.getOriginalFilename()+"文件");
            logger.info("读取"+geneInfo.getSheetName()+"sheet页的excel数据");
            // 读取excel数据
            List<HashMap<Integer ,String>> data = EasyExcel
                    .read(file.getInputStream())
                    .sheet(geneInfo.getSheetName())
                    .headRowNumber(0)
                    .doReadSync();

            // 请求参数list
            List<ReqParam> reqParams = new ArrayList<>();
            // 响应参数list
            List<ResParam> resParams = new ArrayList<>();
            // 读取请求参数标识
            boolean readerReqFlag =false;
            // 读取响应参数标识
            boolean readerResFlag =false;
            for (int i = 0; i < data.size(); i++) {

                HashMap<Integer, String> stringStringHashMap = data.get(i);

                if(stringStringHashMap.containsValue("请求报文")){
                    // 跳过一条
                    i+=1;
                    readerReqFlag = true;
                    continue;
                }
                if(stringStringHashMap.containsValue("响应报文")){
                    // 跳过一条
                    i+=1;
                    readerReqFlag = false;
                    readerResFlag = true;
                    continue;
                }
                // 读取请求报文
                if(readerReqFlag){
                    ReqParam reqParam = new ReqParam();
                    reqParam.setFiledName(stringStringHashMap.get(0));
                    reqParam.setFiledDesc(stringStringHashMap.get(1));
                    reqParams.add(reqParam);
                }
                // 读取响应报文
                if(readerResFlag){
                    String field = stringStringHashMap.get(0).toLowerCase();
                    Matcher matcher = pattern.matcher(field);
                    // 跳过List Row和中文描述的响应报文行
                    if(field.contains("list")||field.contains("row")||matcher.find()|| field.contains("map")){
                        // 跳过一条
                        i+=1;
                        continue;
                    }
                    ResParam resParam = new ResParam();
                    resParam.setFiledName(stringStringHashMap.get(0));
                    resParam.setFiledDesc(stringStringHashMap.get(1));
                    resParams.add(resParam);
                }

            }
            logger.info("读取"+geneInfo.getSheetName()+"成功");
            if(StringUtils.isNotNull(reqParams) && StringUtils.isNotNull(resParams)){
                logger.info("正在生成接口中....");
                GeneratorUtils.generatorInterFace(geneInfo,reqParams,resParams);
                logger.info("生成接口成功!!!");
                ArrayList<GeneInfo> geneInfos = new ArrayList<>();
                geneInfo.setFileName(geneInfo.getClientInterFaceName());
                // 添加客户端下载对象
                geneInfos.add(geneInfo);
                // 创建服务端下载对象
                GeneInfo serverGeneInfo = new GeneInfo();
                BeanUtils.copyProperties(geneInfo,serverGeneInfo);
                serverGeneInfo.setFileName(serverGeneInfo.getServerInterFaceName());
                geneInfos.add(serverGeneInfo);
                return new Result<List<GeneInfo>>(200,geneInfos);
            }else{
                return new Result<List<GeneInfo>>(500, Collections.emptyList());
            }

        }catch (Exception e){
            logger.error("自动生成接口失败",e);
            return new Result<List<GeneInfo>>(500, Collections.emptyList());
        }
    }


    @GetMapping("/downLoadFile")
    public void downLoadFile(@RequestParam("path") String path, @RequestParam("name") String name, HttpServletResponse response) throws Exception {


        logger.info("下载路径为:"+ path);
        response.setContentType("text/html;charset=UTF-8");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        long fileLength = (new File(path)).length();
        response.setContentType("application/octet-stream;charset=GBK");
        response.setHeader("Content-disposition", "attachment; filename=" + new String(name.getBytes("GB2312"), "ISO-8859-1"));
        response.setHeader("Content-Length", String.valueOf(fileLength));
        bis = new BufferedInputStream(new FileInputStream(path));
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];

        int bytesRead;
        while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }

        bis.close();
        bos.close();

    }


}
